function [hist_c, hist_i, rng] = ccv2(data, T, min_max)
%CCV calculate Color Coherence Vector on data (Use BWLABEL).
%   [HIST_C, HIST_I, RNG] = CCV2(DATA, T[, MIN_MAX]) 
    %  data -> input data
    %  T -> threhold
    %  hist_c -> histogram of consistent part
    %  hist_i -> histogram of inconsistent part
    d = double(data(:));
    if nargin < 3
        minval = min(d);
        maxval = max(d);
    else
        minval = min_max(1);
        maxval = min_max(1);
        d(d > maxval) = NaN;
        d(d < minval) = NaN;
    end    
    rng = minval:maxval;
    sz = maxval - minval + 1;
    hist_c = zeros(1, sz);
    hist_i = hist_c;
    
    while 1
        % search minimal value
        val = min(d);
        if isnan(val)
            % all number processed, end loop
            break;
        end
        % find groups of 1 in p
        hc = 0;
        hi = 0;
        bw = (data == val);
        L = bwlabel(bw, 8);
        num_group = max(L(:));
        for i = 1:num_group
            count = length(find(L == i));
            if count >= T
                hc = hc + count;
            else
                hi = hi + count;
            end
        end
        hist_c(val - minval + 1) = hc;
        hist_i(val - minval + 1) = hi;
        % cleanup, use NaN as special value
        d(d == val) = NaN;
    end
    s = sum(hist_c(:)) + sum(hist_i(:));
    if s > 0
        hist_c = hist_c / s;
        hist_i = hist_i / s;
    end
end
